package com.link.base.base.product.model;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.link.core.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 模板的读取类
 *
 * @author Jiaju Zhuang
 */
public class PcdDataCheckListener extends AnalysisEventListener<PcdDataExcelMo> {

    private static final Logger logger = LogManager.getLogger(PcdDataCheckListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    /**
     * 导入的数据集
     * 这里不错缓存处理，目的是校验是否存在重复序号
     */
    private List<String> cachedDataList = new ArrayList<>();


    public PcdDataCheckListener() {

    }

    @Override
    public void invoke(PcdDataExcelMo data, AnalysisContext context) {
        // 校验数据是否正常，并抛出异常
        int i = context.getCurrentRowNum().intValue();
        if (Objects.isNull(data)) {
            logger.error("第{}行，数据不能为空！",i);
            throw new IllegalArgumentException("第" + i + "行" +  "数据不能为空");
        }
        if (StringUtils.isNull(data.getXuHao())) {
            logger.error("第{}行，序号不能为空！",i);
            throw new IllegalArgumentException("第" + i + "行" +  "序号不能为空");
        }
        if (cachedDataList.contains(data.getXuHao())) {
            logger.error("第{}行，{}序号重复，请检查！",i,data.getXuHao());
            throw new IllegalArgumentException("第" + i + "行" + data.getXuHao() + "序号重复，请检查");
        }
        cachedDataList.add(data.getXuHao());
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        logger.error("第{}行，异常信息{}",context.getCurrentRowNum(),exception);
        super.onException(exception, context);
    }

    /**
     * 最后一步
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }
}
